package com.ww.book.javaconcurrencyinpractice.ch03;

/**
 * 安全构造方式
 */
public class SafeConstructor {
    private final int value;
    private final EventListener listener;

    private SafeConstructor() {
        this.value = 42; // 先完成所有初始化

        // 创建监听器，但此时this引用不会逃逸
        this.listener = e -> doSomething(e);
    }

    public static SafeConstructor newInstance(EventSource source) {
        SafeConstructor instance = new SafeConstructor();
        // 对象完全构造完成后才注册监听器
        source.registerListener(instance.listener);
        return instance;
    }

    private void doSomething(Event e) {
        System.out.println("Safe Value: " + value);
    }

    // 打印结果
//    Safe Value: 42
    public static void main(String[] args) {
        EventSource source = new EventSource();
        SafeConstructor instance = SafeConstructor.newInstance(source);
    }
}
